package cn.com.cetccst.appstore.ui.activity.viewmodel;

import android.content.Context;
import android.widget.Toast;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import cn.com.cetccst.appstore.R;
import cn.com.cetccst.appstore.database.AppStoreRepository;
import cn.com.cetccst.appstore.database.model.AppModel;
import cn.com.cetccst.appstore.log.AppStoreLogger;
import cn.com.cetccst.appstore.network.AppStoreHttpRequester;
import cn.com.cetccst.network.BaseCallback;
import cn.com.cetccst.tools.ui.ThreadSafeToast;

public class AppDetailViewModel extends ViewModel {

    public LiveData<Boolean> horizontal = new MutableLiveData<>(true);
    public MutableLiveData<Boolean> loadFailure = new MutableLiveData(false);
    public LiveData<AppModel> appDetail;
    public MutableLiveData<String> publisherName = new MutableLiveData<>();
    public interface Callback {
        void onResult(boolean success);
    }

    public void requestAppDetail(Context context, String appId, Callback callback) {
        AppStoreHttpRequester.getInstance().requestAppDetail(appId, new BaseCallback<>() {
            @Override
            public void onResponse(JsonObject data) {
                if (callback != null)
                    callback.onResult(data != null);

                if (data != null) {
                    loadFailure.setValue(false);
                    AppModel appModel = new Gson().fromJson(data, AppModel.class);
                    appModel.detectAppStatus(context);
                    AppStoreRepository.getInstance().saveAppModel(appModel);
                } else {
                    loadFailure.setValue(true);
                    AppStoreLogger.info("getAppDetail data is null");
                    ThreadSafeToast.show(R.string.store_network_failed, Toast.LENGTH_LONG);
                }
            }
        });
    }

    //TODO 这个方法最恶心，服务器竟然不直接反馈
    public void requestPublisher() {
        //TODO 这个publisherId数据库存的是里面的
        AppStoreHttpRequester.getInstance().requestPublisher(appDetail.getValue().getAppSummary().getAppPublisherId(), new BaseCallback<>() {
            @Override
            public void onResponse(JsonObject data) {
                if (data != null) {
                    JsonElement jsonElement = data.get("name");
                    publisherName.setValue(jsonElement.getAsString());
                } else {
                    AppStoreLogger.info("getAppDetail data is null");
                }
            }
        });
    }
}
